package ii.oo.liu;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Admin on 1/4 0004.
 */
public class NIOTest {
    @Test
    public void test(){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        FileChannel fc1= null;//获取文件通道
        FileChannel fc2= null;
        try {
            File file=new File("a.txt");
            File file2=new File("e.txt");
            fis = new FileInputStream(file);
            fos = new FileOutputStream(file2);
            fc1 = fis.getChannel();//获取文件通道
            fc2 = fos.getChannel();//获取文件通道
            //定义一个Buffer 容器;
            ByteBuffer buffer=ByteBuffer.allocate((int)file.length());
            fc1.read(buffer);//开始读取数据;
            //将缓存字节数组的指针设置为数组的开始序列即数组下标0。
            // 这样就可以从buffer开头，对该buffer进行遍历（读取）了。
            buffer.flip();
            fc2.write(buffer);//写入数据;
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fc1!=null){
                try {
                    fc1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fc2!=null){
                try {
                    fc2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() throws Exception {
        //也可以使用随机存取文件流: RandomAccessFile
        File file=new File("a.txt");
        RandomAccessFile raf1=new RandomAccessFile(file,"r");
        RandomAccessFile raf2=new RandomAccessFile(new File("f.txt"),"rw");
        FileChannel fileChannel=raf1.getChannel();
        FileChannel fileChannel1=raf2.getChannel();
        //映射内存;
        MappedByteBuffer mappedByteBuffer=fileChannel.map(FileChannel.MapMode.READ_ONLY,0,fileChannel.size());
        fileChannel1.write(mappedByteBuffer);
        fileChannel.close();
        fileChannel1.close();
        raf2.close();
        raf1.close();
    }


}
